import { popupNotification } from '../config/mapStyles';
import { layersManager } from './layerManager';
import { popupManager } from './popupManager';
import { rander } from './rander'
import { mapApi } from "../api/mapApi";

let time = []  // 存储开始时间结束时间
let correspondingStartTime: Array<any> = [];  // 每个起始时间对应的模型/模型id
let playbackData: any[] = []  // 存储回放数据
let map: any = null  // 存储地图

// 回放处理  
const playback = {
    // 初始化，加载模型和航迹
    loadfModelTracks(map: any, czml: any) {
        map = map
        time = czml.clock.interval.split('/')  // 获取开始时间和结束时间
        console.log(czml);

        czml.data.forEach((item: any) => {
            const { pointId, polylineId } = this.getIds(item.id)  // 获取id
            playbackData.push({ // 存储回放数据
                modelId: pointId,
                polylineId: polylineId,
                position: item.position.coordinate,
                information: item.position.information,
                time: item.position.time
            })
            const saveIndex = correspondingStartTime.findIndex(m => m.id == pointId)
            if (saveIndex < 0) {
                correspondingStartTime?.push({ timeReally: item.epoch, id: pointId })  // 存储对应模型起始时间和id,方便后续查找
                console.log('添加' + polylineId, pointId);
            }

            rander.geometryManager.drawPolyline(map, polylineId, [])  // 加载航迹
            rander.geometryManager.drawPoint(map, pointId, item.position.coordinate[0])  // 加载模型

        })
    },
    // 回放移动
    moveModel(currentTime: number) {
        // 判断map是否为空
        if (map == null) {
            map = mapApi.map.getMap()
        }
        correspondingStartTime.forEach((item: any) => {
            // 计算相对时间 转换为索引
            let timeIndex = (currentTime - item.timeReally) / 1000
            // 获取对应的模型
            const currentModel = playbackData.find(m => m.modelId == item.id)
            // timeIndex > 0 表示当前时间大于模型起始时间, 则显隐状态为true
            if (timeIndex > 0) {
                // 符合条件则进行显隐
                this.changeModelShow(map, currentModel.modelId)
                this.changeModelShow(map, currentModel.polylineId)
                // 获取当前时间对应的坐标
                // 判断符合时间段的数据
                if (timeIndex > 0 && timeIndex < currentModel.position.length - 1) {
                    this.changePosition(currentModel, timeIndex)  // 移动模型  
                    const { updateModelId, information, coordinate } = { updateModelId: currentModel.modelId, information: currentModel.information[timeIndex], coordinate: currentModel.position[timeIndex] }
                    this.popupManager(map, updateModelId, information, coordinate)  // 弹窗
                }

            } else {
                // timeIndex < 0 表示当前时间小于模型起始时间, 则显隐状态为false
                this.changeModelHide(map, currentModel.modelId)
                this.changeModelHide(map, currentModel.polylineId)
            }

        })
    },
    // 改变模型可见 
    changeModelShow(map: any, id: string) {
        const isVisible = layersManager.getVisible(map, id)
        if (isVisible == 'none') {
            layersManager.toggleLayerVisibility(map, id)
        }
    },
    // 改变模型不可见
    changeModelHide(map: any, id: string) {
        const isVisible = layersManager.getVisible(map, id)
        if (isVisible == 'visible') {
            layersManager.toggleLayerVisibility(map, id)
        }
    },
    // 获取当前模型id，航迹id
    getIds(id: string) {
        return {
            pointId: id + "_callbackPoint",
            polylineId: id + "_callbackPolyline"
        }
    },
    // 改变位置
    changePosition(currentModelData: any, currentIndex: number) {
        // 获取当前时间对应的坐标
        const { updateModelId, updatePolylineId, updateCoordinate, information } = { updateModelId: currentModelData.modelId, updatePolylineId: currentModelData.polylineId, updateCoordinate: currentModelData.position[currentIndex].map((item: any) => Number(item)), information: currentModelData.information[currentIndex] }
        // 移动模型

        map?.getSource(updateModelId)?.setData({
            type: 'FeatureCollection',
            features: [{
                type: 'Feature',
                geometry: {
                    type: 'Point',
                    coordinates: updateCoordinate
                },
                properties: {
                    ...information
                }
            }]
        });
        // 获取航迹信息
        const polylineData = currentModelData.position.slice(0, currentIndex)
        // 移动航迹
        map?.getSource(updatePolylineId)?.setData({
            "type": "FeatureCollection",
            "features": [{
                "type": "Feature",
                "geometry": {
                    "type": "LineString",
                    "coordinates": polylineData
                }
            }]
        })


    },
    // popup 显示，管理
    popupManager(map: any, id: string, information: any, coordinate: any) {
        const popupId = id + "_popup"
        //  获取popup
        const popup = popupManager.getPopupById(popupId);
        // 获取popup位置
        const popupPosition = coordinate
        // 如果popup不存在，则创建popup
        if (!popup) {
            // 添加popup
            popupManager.createPopup(map, popupId, popupPosition, `<div></div>`)
        }
        // 更新popup 位置
        popupManager.updatePopupPositition(popupId, popupPosition)
        const options = { longitude: popupPosition[0], latitude: popupPosition[1] };
        // 更新内容
        popupManager.updatePopup(popup, popupNotification.realTimeLayer(options))
    },
    remove(map: any, id: string) {
        const ids = this.getIds(id)
        const deletIndex = correspondingStartTime.findIndex(m => m.id == ids.pointId)
        correspondingStartTime.splice(deletIndex, 1)
        layersManager.removeLayer(map, ids.pointId)
        layersManager.removeLayer(map, ids.polylineId)
        popupManager.closePopup(id + "_callbackPoint_popup")

    }
}


export { playback } // 导出